<?php
/**
 * Created by PhpStorm.
 * Author: 芸签cms www.yunqiancms.com
 * User: sun
 * Date: 2022/6/24
 * Time: 2:54 PM
 */
namespace app\common\services;


class QcloudCosClient extends \Qcloud\Cos\Client
{
    public static $regionMap = [
        'ap-nanjing'=>'南京',
        'ap-guangzhou'=>'广州',
        'ap-chengdu'=>'成都',
        'ap-beijing'=>'北京',
        'ap-chongqing'=>'重庆',
        'ap-shanghai'=>'上海',
        'ap-hongkong'=>'香港',
        'ap-shanghai-fsi'=>'北京金融',
        'ap-shanghai-fsi'=>'上海金融',
        'ap-shenzhen-fsi'=>'深圳金融',
    ];

    /**
     * 根据中文获取region
     * @param $name
     * @return mixed
     */
    public static function getRegionByName($name){
        $regions = array_flip(self::$regionMap);
        return $regions[$name];
    }

    /**
     * 获取region列表，key:value
     * @return array
     */
    public static function getRegionList(){
        $res = [];
        foreach (self::$regionMap as $k=>$v){
            $resTmp = [];
            $resTmp['key'] = $k;
            $resTmp['value'] = $v;
            array_push($res,$resTmp);
        }
        return $res;
    }

    /**
     * 上传文件
     * @param $bucket
     * @param $srcPath
     * @param $dstPath
     * @return object|string
     */
    public function uploadFile($bucket, $srcPath,$dstPath)
    {
        try {
            $result = parent::putObject(array(
                'Bucket' => $bucket,
                'Key' => $dstPath,
                'Body' => file_get_contents($srcPath),
            ));
            return $result;
        }catch (\Qcloud\Cos\Exception\ServiceResponseException $e){
            \Log::error('app:common:services:QcloudCosClient:uploadFile:ServiceResponseException:StatusCode:CosErrorCode', $e->getStatusCode().':'.$e->getCosErrorCode());
            \Log::error('app:common:services:QcloudCosClient:uploadFile:getMessage', $e->getMessage());
        }catch (\Exception $e) {
            \Log::error('app:common:services:QcloudCosClient:uploadFile:Exception', $e->getMessage());
            return $e->getMessage();
        }
    }
    /**
     * 删除文件
     * @param $bucket
     * @param $dstPath
     * @return object|string
     */
    public function deleteFile($bucket,$dstPath)
    {
        try {
            $result = parent::deleteObject(array(
                'Bucket' => $bucket,
                'Key' => $dstPath
            ));
            return $result;
        } catch (\Exception $e) {
            \Log::error('app:common:services:QcloudCosClient:deleteFile:Exception', $e->getMessage());
            return $e->getMessage();
        }
    }
}